/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.csp.sentinel.dashboard.rule.nacos;

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.ApiDefinitionEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.AuthorityRuleEntityStore;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.DegradeRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.SystemRuleEntity;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigFactory;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collectors;

/**
 * @author Eric Zhao
 * @since 1.4.0
 */
@EnableConfigurationProperties(NacosPropertiesConfiguration.class)
@Configuration
public class NacosConfig {

    @Bean
    public Converter<List<FlowRuleEntity>, String> flowRuleEntityEncoder() {
        return rule -> JSON.toJSONString(rule, true);
    }

    @Bean
    public Converter<String, List<FlowRuleEntity>> flowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, FlowRuleEntity.class);
    }

    @Bean
    public Converter<List<AuthorityRuleEntity>, String> authRuleEntityEncoder() {
        return rules -> {
            List<AuthorityRuleEntityStore> ruleList = rules.stream().map(this::mapToAuthorityRuleEntityStore)
                    .collect(Collectors.toList());
            return JSON.toJSONString(ruleList, true);
        };
    }

    @Bean
    Converter<String, List<AuthorityRuleEntity>> authRuleEntityDecoder() {
        return s -> JSON.parseArray(s, AuthorityRuleEntityStore.class).stream()
                .map(this::mapToAuthorityRuleEntity).collect(Collectors.toList());
    }

    @Bean
    public Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {
        return rule -> JSON.toJSONString(rule, true);
    }

    @Bean
    public Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {
        return s -> JSON.parseArray(s, DegradeRuleEntity.class);
    }

    @Bean
    public Converter<List<ParamFlowRuleEntity>, String> paramsRuleEntityEncoder() {
        return rule -> JSON.toJSONString(rule, true);
    }

    @Bean
    public Converter<String, List<ParamFlowRuleEntity>> paramsRuleEntityDecoder() {
        return s -> JSON.parseArray(s, ParamFlowRuleEntity.class);
    }

    @Bean
    public Converter<List<SystemRuleEntity>, String> systemRuleEntityEncoder() {
        return rule -> JSON.toJSONString(rule, true);
    }

    @Bean
    public Converter<String, List<SystemRuleEntity>> systemRuleEntityDecoder() {
        return s -> JSON.parseArray(s, SystemRuleEntity.class);
    }

    @Bean
    public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
        return source -> JSON.toJSONString(source
                .stream()
                .peek(rule -> rule.setIntervalSec(GatewayFlowRuleEntity.calIntervalSec(rule.getInterval(), rule.getIntervalUnit())))
                .collect(Collectors.toList()), true);
    }


    @Bean
    Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {
        return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);
    }

    @Bean
    public Converter<List<ApiDefinitionEntity>, String> gatewayApiRuleEntityEncoder() {
        return rule -> JSON.toJSONString(rule, true);
    }


    @Bean
    Converter<String, List<ApiDefinitionEntity>> gatewayApiRuleEntityDecoder() {
        return s -> JSON.parseArray(s, ApiDefinitionEntity.class);
    }

    @Bean
    public ConfigService nacosConfigService(NacosPropertiesConfiguration nacosPropertiesConfiguration) throws Exception {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, nacosPropertiesConfiguration.getServerAddr());
        properties.put(PropertyKeyConst.NAMESPACE, nacosPropertiesConfiguration.getNamespace());
        properties.put(PropertyKeyConst.USERNAME, nacosPropertiesConfiguration.getUsername());
        properties.put(PropertyKeyConst.PASSWORD, nacosPropertiesConfiguration.getPassword());
        return ConfigFactory.createConfigService(properties);
    }

    private AuthorityRuleEntity mapToAuthorityRuleEntity(AuthorityRuleEntityStore authorityRuleStore) {
        AuthorityRuleEntity ruleEntity = new AuthorityRuleEntity();
        ruleEntity.setId(authorityRuleStore.getId());
        ruleEntity.setApp(authorityRuleStore.getApp());
        ruleEntity.setIp(authorityRuleStore.getIp());
        ruleEntity.setPort(authorityRuleStore.getPort());
        ruleEntity.setGmtCreate(authorityRuleStore.getGmtCreate());
        ruleEntity.setGmtModified(authorityRuleStore.getGmtModified());

        AuthorityRule rule = new AuthorityRule();
        rule.setStrategy(authorityRuleStore.getStrategy());
        rule.setResource(authorityRuleStore.getResource());
        rule.setLimitApp(authorityRuleStore.getLimitApp());
        ruleEntity.setRule(rule);

        return ruleEntity;
    }

    private AuthorityRuleEntityStore mapToAuthorityRuleEntityStore(AuthorityRuleEntity rule) {
        AuthorityRuleEntityStore store = new AuthorityRuleEntityStore();
        store.setApp(rule.getApp());
        store.setIp(rule.getIp());
        store.setPort(rule.getPort());
        store.setId(rule.getId());
        store.setGmtCreate(rule.getGmtCreate());
        store.setGmtModified(rule.getGmtModified());

        store.setLimitApp(rule.getRule().getLimitApp());
        store.setStrategy(rule.getRule().getStrategy());
        store.setResource(rule.getRule().getResource());

        return store;
    }
}
